/**
 * @description 折线图
 * 折
 * 折滑 smooth
 * 折面 areaStyle
 * 折滑面 smooth areaStyle 
 */

import echarts from "../echart"
import { useEffect, useRef } from 'react';
import useChartResize from "@/hooks/useChartResize";
import { getLineMock } from "../mockData";

// window.onerror = function (message, source, lineno, colno, error) {
//   console.error("Global error caught:", message);
//   // 处理错误
// };

// window.addEventListener('unhandledrejection', function (event) {
//   console.error("Unhandled promise rejection:", event.reason);
//   // 处理错误
// });

function Line({ configData, chart }) {

  let { title, graphType } = configData

  const chartRef = useRef(null)
  const boxRef = useRef()


  useEffect(() => {

    // 图表配置项
    let themeConfig = chart.line

    // 限制数量
    let limitNum = chart.base.lineNum

    // 基于准备好的dom，初始化echarts实例
    if (!chartRef.current) {
      let myChart = echarts.init(boxRef.current)
      chartRef.current = myChart
    }

    // [1] 获取随机数据
    let [xAxisData, yAxisData] = getLineMock(limitNum)

    // [2] 配置项
    let seriesObj = {
      ...themeConfig.series,
      data: yAxisData,
      type: 'line',
    }

    /**
     * smooth 控制平滑
     * areaStyle  控制面积， {} 空对象由系统自动生成对应的主题颜色
     */
    switch (graphType) {

      case '折':
        seriesObj.smooth = false
        delete seriesObj.areaStyle
        break;

      case '折滑':
        seriesObj.smooth = true
        delete seriesObj.areaStyle
        break;

      case '折面':
        seriesObj.smooth = false
        if (!seriesObj.areaStyle) {
          seriesObj.areaStyle = {}
        }

        break;

      case '折滑面':
        seriesObj.smooth = true
        if (!seriesObj.areaStyle) {
          seriesObj.areaStyle = {}
        }
        break;
    }

    const options = {
      backgroundColor: themeConfig.backgroundColor,
      color: themeConfig.color,
      title: {
        ...themeConfig.title,
        text: title,
      },
      // 图例组件
      legend: themeConfig.legend,
      // 直角坐标系内绘图网格
      // grid: themeConfig.grid,
      // 提示框组件
      tooltip: {
        ...themeConfig.tooltip
      },
      // x轴
      xAxis: {
        ...themeConfig.xAxis,
        type: 'category',
        boundaryGap: false,
        data: xAxisData
      },
      // y轴
      yAxis: {
        ...themeConfig.yAxis,
        type: 'value'
      },
      series: [seriesObj]
    }

    // 绘制图表
    chartRef.current.setOption(options, true);


  }, [chart])


  useChartResize(boxRef, chartRef)

  return (
    <div className='chart-box' ref={boxRef} ></div>
  )
}

export default Line